package com.xzp.gkrpc.transprot;


import lombok.extern.slf4j.Slf4j;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class HttpTransportServer implements TransportServer{
    private RequestHandler requestHandler;
    private Server server;

    @Override
    public void start() {
        try {
            server.start();
            server.join();
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        try {
            server.stop();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void init(int port, RequestHandler handler) {

        this.requestHandler = handler;
        // servlet接受请求
        this.server = new Server(port);

        ServletContextHandler servletContextHandler = new ServletContextHandler();
        server.setHandler(servletContextHandler);
        // 创建一个ServletHolder托管我们的RequestServlet对象
        ServletHolder holder = new ServletHolder(new RequestServlet());
        // 在ServletContextHandler上添加一个ServletHolder处理业务
        servletContextHandler.addServlet(holder, "/*");
    }
    class RequestServlet extends HttpServlet {
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            log.info("client connect");
            ServletInputStream inputStream = req.getInputStream();
            ServletOutputStream outputStream = resp.getOutputStream();
            if(requestHandler != null){
                log.info("start deal with request");
                // 通过requestHandler处理输入请求 并返回输出
                requestHandler.onRequest(inputStream, outputStream);
            }
            outputStream.flush();
        }
    }
}
